package com.chatplus.application.web.converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.format.DateTimeParseException;

@Component
public class TimestampStringToInstantConverter implements Converter<String, Instant> {
    @SuppressWarnings("NullableProblems")
    @Override
    public Instant convert(String source) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }

        if (StringUtils.isNumeric(source)) {
            return Instant.ofEpochMilli(Long.parseLong(source));
        } else {
            try {
                return Instant.parse(source);
            } catch (DateTimeParseException ex) {
                throw new IllegalArgumentException(ex);
            }
        }
    }
}
